import { getCategoryFilterAPI,getSubCategoryAPI } from '@/apis/category'
import { onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'

export function useSubCategory (){
    // 获取面包屑导航数据
    const route = useRoute()
    const filterData = ref([])
    const getFileDate = async () =>{
        const res = await getCategoryFilterAPI(route.params.id)
        // console.log(res.data.result);
        filterData.value = res.data.result
    }
    onMounted(()=>{
        getFileDate()
    })
    // 获取基础列表数据
    const goodList = ref([])
    const reqData = ref({
        categoryId: route.params.id ,
        page: 1,
        pageSize: 20,
        sortField: 'publishTime' 
    })
    const getGoodList = async () => {
        const res = await getSubCategoryAPI(reqData.value)
        // console.log(res);
        goodList.value = res.data.result.items
    }
    onMounted(()=>getGoodList())

    // tab切换回调
    const handClick = () => {
    // console.log('tab切换了', reqData.value.sortField)
    reqData.value.page = 1
    getGoodList()
    }
    // 加载更多(无限滚动，将第二页即后面页数内容加载)
    // 需要element的无限滚动v-infinite-scroll="load"(滚动触发)
    // 禁用element的无限滚动加载 :infinite-scroll-disabled="disabled"
    const disabled = ref(false)
    const load = async () => {
    // console.log('加载更多数据咯')
    // 获取下一页的数据
    reqData.value.page++
    const res = await getSubCategoryAPI(reqData.value)
    goodList.value = [...goodList.value, ...res.data.result.items]
    // 加载完毕 停止监听(没有数据时)
    if (res.data.result.items.length === 0) {
        disabled.value = true
    }
    }
    onMounted(()=>load())

    return{
        goodList,handClick,load,reqData,disabled,filterData
    }
}




